/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.framework.product;

import com.alibaba.fastjson2.JSON;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaRbacService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.service.framework.product.ProductService;
import com.je.rbac.rpc.RoleRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/je/meta/product/plan/manage")
public class PlanProductManageController extends AbstractPlatformController {

    @Autowired
    private ProductService productService;
    @Autowired
    private RoleRpcService roleRpcService;
    @Autowired
    private MetaRbacService metaRbacService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        if (param.getLimit() == 0) {
            param.setLimit(-1);
        }

        //分页对象
        Page page = new Page<>(param.getPage(), param.getLimit());
        String funcCode = param.getFuncCode();
        //构建查询条件
        Query query = param.buildQuery();
//        commonService.buildProductQuery(query,"JE_PRODUCT_MANAGE_ID");
        param.setjQuery(JSON.toJSONString(query));
        ConditionsWrapper wrapper = manager.buildWrapper(param, request);
        List<Map<String, Object>> list = metaService.load(funcCode, page, wrapper);
        //2023.1.3 去掉人员过滤
        /*List<Map<String, Object>> resultList = new ArrayList<>();
        String realUserId = SecurityUserHolder.getCurrentAccountRealUserId();
        String departmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
        List<DynaBean> dynaBean = metaRbacService.selectByNativeQuery(NativeQuery.build().tableCode("JE_RBAC_VUSERQUERY").eq("USER_ID", realUserId).eq("DEPARTMENT_ID", departmentId));
        String accountdeptId = "";
        if (dynaBean != null && dynaBean.size() > 0) {
            accountdeptId = dynaBean.get(0).getStr("JE_RBAC_ACCOUNTDEPT_ID");
        }
        for (Map<String, Object> map : list) {
            if (!((map.get("PRODUCT_DEVELOPER_ID")) == null ? "" : (map.get("PRODUCT_DEVELOPER_ID").toString())).contains(accountdeptId)) {
                continue;
            }
            resultList.add(map);
        }*/
        return BaseRespResult.successResultPage(list, Long.valueOf(list.size()));
    }

    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean bean = productService.doSave(param, request);
        return BaseRespResult.successResult(bean.getValues());
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean bean = productService.doUpdate(param, request);
        return BaseRespResult.successResult(bean.getValues());
    }

    @Override
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String productId = getStringParameter(request, "ids");
        if (Strings.isNullOrEmpty(productId)) {
            return BaseRespResult.errorResult("请选择要移除的产品！");
        }
        List<DynaBean> productRoleList = roleRpcService.findProductDevelopRoles(Splitter.on(",").splitToList(productId));
        if (productRoleList != null && !productRoleList.isEmpty()) {
            return BaseRespResult.errorResult("请先移除产品开发者角色！");
        }
        return super.doRemove(param, request);
    }

    @RequestMapping(value = "/planBeforeSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult planBeforeSave(BaseMethodArgument param, HttpServletRequest request) {
        String productCode = getStringParameter(request, "productCode");
        String pkValue = getStringParameter(request, "pkValue");
        if (Strings.isNullOrEmpty(productCode)) {
            return BaseRespResult.errorResult("请先输入产品编码！");
        }
        List<DynaBean> productDynaBean = null;
        if (Strings.isNullOrEmpty(pkValue)) {
            productDynaBean = metaService.select("JE_PRODUCT_MANAGE", ConditionsWrapper.builder().eq("PRODUCT_CODE", productCode));
            if (!productDynaBean.isEmpty()) {
                return BaseRespResult.errorResult("产品编码重复，请重新输入编码！");
            }
        } else {
            productDynaBean = metaService.select("JE_PRODUCT_MANAGE", ConditionsWrapper.builder().eq("PRODUCT_CODE", productCode));
            if (productDynaBean.size() > 1) {
                return BaseRespResult.errorResult("产品编码重复，请重新输入编码！");
            }
        }
        return BaseRespResult.successResult("验证成功！");
    }

}
